package com.nettest.action.usermanage;

import java.util.ArrayList;
import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.json.annotations.JSON;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;

import com.nettest.action.BaseJsonAction;
import com.nettest.bean.usermanage.UserCriteriaVo;
import com.nettest.bean.web.TreeVo;
import com.nettest.entity.system.Role;
import com.nettest.service.usermanage.RoleService;
import com.nettest.util.AppUtil;

@Results({
		@Result(name = "input", type = "json", params = { "ignoreHierarchy",
				"false", "excludeNullProperties", "true", "excludeProperties",
				"roleService,ids" }),
		@Result(name = "success", location = "/usermanage/grantPermission.jsp") })
@Namespace("/usermanage/role")
public class RoleManageAction extends BaseJsonAction {

	private static final long serialVersionUID = 7796054923782630546L;
	private UserCriteriaVo criteria;

	private Role data;
	
	private List<Role> lists;
	
	private List<TreeVo> trees;
	@Autowired
	private RoleService roleService;
	
	private String ids;
	public RoleManageAction() {
		super();
	}

	@SuppressWarnings("unchecked")
	@Action(value = "list", results = { @Result(name = "success", type = "json", params = {
			"ignoreHierarchy", "false", "excludeNullProperties", "true",
			"excludeProperties", "criteria" }) })
	public String list() {
		int intPage = getPage();
		int intRows = getRows();
		int firstResult = intPage * intRows - intRows;
		if(criteria == null) criteria = new UserCriteriaVo(); 	
		criteria.setPageSize(firstResult);
		criteria.setPageNo(intRows);
		criteria.setSortField(getSort());
		criteria.setDescOrAsc(getOrder());
		try {
			this.lists = (List<Role>)roleService.queryByCriteria(criteria);
			setTotal(roleService.totalSize(criteria));
			setSuccess(true);
		} catch (Exception e) {
			setSuccess(false);
			this.addActionMessage(e.getMessage());
		}
		return SUCCESS;
	}
	
	@SuppressWarnings("unchecked")
	@Action(value = "getGrantXml", results = { @Result(name = "success", type = "json", params = {
			"ignoreHierarchy", "false", "excludeNullProperties", "true",
			"excludeProperties", "criteria,lists" }) })
	public String grantTreeXml() {
		String parameter = getRequest().getParameter("roleId");
		if(parameter == null) return null;
		Long roleId = Long.valueOf(parameter);
		try {
			/*Role role = roleService.get(roleId);
			String functions = role.getMenus();
			functions = functions == null ? "" : functions;
			Document menuDocument = AppUtil.getGrantMenuDocument();
			Element localElement1 = menuDocument.getRootElement();
			List<Element> localList = localElement1.selectNodes("/Modules/Menus/Items");
			
			this.trees = buildGrantTree(localList,"Items",functions);
			setSuccess(true);*/
		} catch (Exception e) {
			setSuccess(false);
			this.addActionMessage(e.getMessage());
		}
		return SUCCESS;
	}
	@Action(value = "saveGrantPermission", results = { @Result(name = "success", type = "json", params = {
			"ignoreHierarchy", "false", "excludeNullProperties", "true",
			"excludeProperties", "criteria,lists,trees" }) })
	public String saveGrantPermission() {
		String parameter = getRequest().getParameter("roleId");
		String functions = getRequest().getParameter("functions");
		if(parameter == null) return null;
		Long roleId = Long.valueOf(parameter);
		try {
			Role role = roleService.get(roleId);
			/*role.setFunctions(functions);*/
			roleService.save(role);
			setSuccess(true);
		} catch (Exception e) {
			setSuccess(false);
			this.addActionMessage(e.getMessage());
		}
		return SUCCESS;
	}
	
	@SuppressWarnings("unchecked")
	protected List<TreeVo> buildGrantTree(List<Element> selectNodes,String xpath, String functions) {
		List<TreeVo> treevos = new ArrayList<TreeVo>();
		for (int i = 0; i < selectNodes.size(); ++i) {
			Element element = (Element) selectNodes.get(i);
			String elementName = element.getName();
			TreeVo rootTree = new TreeVo();
			Attribute attributeId = element.attribute("id");
			String treeId = attributeId.getValue();
			if(functions.indexOf("__ALL") != -1) {
				rootTree.setChecked(true);
			}
			if(functions.indexOf(treeId) != -1) {
				rootTree.setChecked(true);
			}
			Attribute attributeText = element.attribute("text");
			Attribute attributeIconCls = element.attribute("iconCls");
			rootTree.setId(attributeId.getValue());
			rootTree.setText(attributeText.getValue());
			rootTree.setIconCls(attributeIconCls.getValue());
			
			if("Items".equals(elementName)) {
				xpath = "./Item";
			} else if("Item".equals(elementName)) {
				xpath = "./Function";
			}
			List<Element> selectNodes2 = element.selectNodes(xpath);
			rootTree.setChildren(buildGrantTree(selectNodes2,xpath,functions));
			
			treevos.add(rootTree);
		}
		return treevos;
	}
	
	@Action(value = "save", results = { @Result(name = "success", type = "json", params = {
			"ignoreHierarchy", "false", "excludeNullProperties", "true",
			"excludeProperties", "criteria" }) })
	public String save() {
		try {
			if(data.getId() != null) {
				//update case
				Role updateData = roleService.get(data.getId());
				updateData.setRoleId(data.getRoleId());
				updateData.setRoleName(data.getRoleName());
				this.data = (Role)roleService.save(updateData);
			} else {
				// new case
				this.data = (Role)roleService.save(data);
			}
			setSuccess(true);
		} catch (Exception e) {
			setSuccess(false);
			e.printStackTrace();
			this.addActionMessage(e.getMessage());
		}
		return SUCCESS;
	}
	@Action(value = "delete", results = { @Result(name = "success", type = "json", params = {
			"ignoreHierarchy", "false", "excludeNullProperties", "true",
			"excludeProperties", "criteria,data,list" }) })
	public String delete() {
		try {
			if(ids != null) {
				String[] split = ids.split(",");
				for (int i = 0; i < split.length; i++) {
					roleService.delete(Long.valueOf(split[i]));
				}
			}
			setSuccess(true);
		} catch (Exception e) {
			setSuccess(false);
			e.printStackTrace();
			this.addActionMessage(e.getMessage());
		}
		return SUCCESS;
	}
	
	public void validateSave() {
	}
	public UserCriteriaVo getCriteria() {
		return criteria;
	}

	public void setCriteria(UserCriteriaVo criteria) {
		this.criteria = criteria;
	}

	public Role getData() {
		return data;
	}

	public void setData(Role data) {
		this.data = data;
	}

	@JSON(name="rows")
	public List<Role> getLists() {
		return lists;
	}

	public void setLists(List<Role> lists) {
		this.lists = lists;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public List<TreeVo> getTrees() {
		return trees;
	}

	public void setTrees(List<TreeVo> trees) {
		this.trees = trees;
	}
}